package com.micro.ai.template.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.micro.ai.commons.domain.ApiResponse;
import com.micro.ai.template.entity.ExecutionLog;
import com.micro.ai.template.service.ExecutionLogService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 执行日志Controller
 *
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/api/execution/logs")
@RequiredArgsConstructor
@Tag(name = "执行日志管理", description = "执行日志相关接口")
public class ExecutionLogController {

    private final ExecutionLogService executionLogService;

    @PostMapping
    @PreAuthorize("hasAuthority('execution:log:create')")
    @Operation(summary = "创建执行日志", description = "创建新的执行日志记录")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "创建成功",
            content = @Content(schema = @Schema(implementation = ExecutionLog.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<ExecutionLog> createLog(@Valid @RequestBody ExecutionLog executionLog) {
        log.info("创建执行日志请求, requestId: {}", executionLog.getRequestId());
        return ApiResponse.success(executionLogService.createLog(executionLog));
    }

    @PutMapping("/{logId}")
    @PreAuthorize("hasAuthority('execution:log:update')")
    @Operation(summary = "更新执行日志", description = "更新执行日志记录")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "更新成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "日志不存在")
    })
    public ApiResponse<Void> updateLog(
            @Parameter(description = "日志ID") @PathVariable String logId,
            @Valid @RequestBody ExecutionLog executionLog) {
        log.info("更新执行日志请求, logId: {}", logId);
        executionLogService.updateLog(logId, executionLog);
        return ApiResponse.<Void>success(null);
    }

    @GetMapping("/execution/{executionId}")
    @PreAuthorize("hasAuthority('execution:log:query')")
    @Operation(summary = "查询执行日志", description = "根据执行ID查询日志列表")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<IPage<ExecutionLog>> getLogsByExecutionId(
            @Parameter(description = "执行ID") @PathVariable String executionId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer size) {
        Page<ExecutionLog> page = new Page<>(current, size);
        return ApiResponse.success(executionLogService.getLogsByExecutionId(executionId, page));
    }

    @GetMapping("/agent/{agentId}")
    @PreAuthorize("hasAuthority('execution:log:query')")
    @Operation(summary = "查询Agent日志", description = "根据Agent ID查询日志列表")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<IPage<ExecutionLog>> getLogsByAgentId(
            @Parameter(description = "Agent ID") @PathVariable String agentId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer size) {
        Page<ExecutionLog> page = new Page<>(current, size);
        return ApiResponse.success(executionLogService.getLogsByAgentId(agentId, page));
    }

    @GetMapping("/agent/{agentId}/statistics")
    @PreAuthorize("hasAuthority('execution:log:query')")
    @Operation(summary = "查询执行统计", description = "获取Agent的执行统计信息")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "Agent不存在")
    })
    public ApiResponse<Map<String, Object>> getStatistics(
            @Parameter(description = "Agent ID") @PathVariable String agentId,
            @Parameter(description = "统计天数") @RequestParam(defaultValue = "7") int days) {
        return ApiResponse.success(executionLogService.getStatistics(agentId, days));
    }

    @DeleteMapping("/clean")
    @PreAuthorize("hasAuthority('execution:log:delete')")
    @Operation(summary = "清理过期日志", description = "清理指定天数之前的日志")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "清理成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<Map<String, Integer>> cleanExpiredLogs(
            @Parameter(description = "保留天数") @RequestParam(defaultValue = "30") int days) {
        log.info("清理过期日志请求, days: {}", days);
        int count = executionLogService.cleanExpiredLogs(days);
        
        Map<String, Integer> result = new HashMap<>();
        result.put("deletedCount", count);
        
        return ApiResponse.success(result);
    }
}

